import logging
import configparser
import os

"""
CRITICAL > ERROR > WARNING > INFO > DEBUG
"""

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CFG = "config.ini"

rawconfig = configparser.RawConfigParser()
rawconfig.read(os.path.join(BASE_DIR, CFG))

LOGLEVEL = rawconfig.get("LOG_Config", "loglevel")
FILENAME = rawconfig.get("LOG_Config", "filename")
FORMAT = rawconfig.get("LOG_Config", "format")
level_relations = {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL,
}


class LOG(object):
    """
    1. log = LOG('filename.log').logger => log.debug('Hi')
    2. log = LOG('filename.log') => log.logger.errer('Oh')

    Params:
    :filename: log储存文件
    :level: log等级（debug、info、warning、error、critical）
    :fmt: log格式
    """

    def __init__(self, filename=FILENAME, level=LOGLEVEL, fmt=FORMAT):
        self.logger = logging.getLogger(filename)
        self.logger.setLevel(level_relations[level])
        format_str = logging.Formatter(fmt)

        shdler = logging.StreamHandler()
        shdler.setFormatter(format_str)

        fhdler = logging.FileHandler(filename=filename)
        fhdler.setFormatter(format_str)

        self.logger.addHandler(shdler)
        self.logger.addHandler(fhdler)
